package q289_gameOfLife;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, -1}, {-1, 1}, {1, -1}};
    public void gameOfLife(int[][] board) {
        List<int[]> change = new ArrayList<>();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (checkState(board, i, j)) change.add(new int[] {i, j});
            }
        }
        for (int[] loc : change) board[loc[0]][loc[1]] = 1 - board[loc[0]][loc[1]];

    }

    private boolean checkState(int[][] board, int i, int j) {
        int liveCell = 0;
        if (board[i][j] == 0) {
            for (int[] dir : dirs) {
                int x = i + dir[0], y = j + dir[1];
                if (x >= 0 && x < board.length && y >= 0 && y < board[0].length && board[x][y] == 1) ++liveCell;
            }
            return liveCell == 3;
        } else {
            for (int[] dir : dirs) {
                int x = i + dir[0], y = j + dir[1];
                if (x >= 0 && x < board.length && y >= 0 && y < board[0].length && board[x][y] == 1) ++liveCell;
            }
            return liveCell < 2 || liveCell > 3;
        }
    }
}
